﻿namespace mgen_commonDlg
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls.Primitives;

    using WinForms = System.Windows.Forms;

    [TemplatePart(Name = PART_Button, Type = typeof(ButtonBase))]
    public class OpenFolderControl : CommonDialogControl
    {
        #region Fields

        WinForms.FolderBrowserDialog dlg;

        #endregion Fields

        #region Constructors

        static OpenFolderControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(OpenFolderControl), new FrameworkPropertyMetadata(typeof(OpenFolderControl)));
        }

        public OpenFolderControl()
        {
            Unloaded += OpenFolderDialog_Unloaded;
        }

        #endregion Constructors

        #region Methods

        public override sealed void Browse()
        {
            dlg = new WinForms.FolderBrowserDialog();
            dlg.SelectedPath = Path;

            var res = dlg.ShowDialog() == WinForms.DialogResult.OK;
            OnShown(res);
            if (res == true)
            {
                Path = dlg.SelectedPath;
                OnOpened();
            }
        }

        void OpenFolderDialog_Unloaded(object sender, RoutedEventArgs e)
        {
            if (dlg != null)
                dlg.Dispose();
        }

        #endregion Methods
    }
}